package me.lx

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.SparseArray
import android.view.LayoutInflater
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.withResumed
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.ThreadUtils
import com.blankj.utilcode.util.Utils
import com.bumptech.glide.Glide
import com.tencent.smtt.export.external.interfaces.WebResourceRequest
import com.tencent.smtt.export.external.interfaces.WebResourceResponse
import com.tencent.smtt.sdk.WebSettings
import com.tencent.smtt.sdk.WebView
import com.tencent.smtt.sdk.WebViewClient
import com.webuy.webview.dsbrige.DWebView
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import me.lx.databinding.ActMainBinding
import me.lx.tools.GlideImageUtils
import me.lx.vm.MainViewModel
import okhttp3.MediaType.Companion.toMediaType
import timber.log.Timber

class MainActivity : AppCompatActivity() {
    lateinit var binding: ActMainBinding
    lateinit var dwebView: DWebView
    lateinit var dwebView2: DWebView
    var webView: WebView? = null
    lateinit var nativeWebView: com.tencent.smtt.sdk.WebView

    val vm by lazy { ViewModelProvider(this).get(MainViewModel::class.java) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.inflate(LayoutInflater.from(this), R.layout.act_main, null, false)
        setContentView(binding.root)
        initView()
        initWebViewSet(dwebView.settings)
        initWebViewSet(dwebView2.settings)
        initGlideView()
        initWebViewClient(dwebView)
    }

    private fun initWebViewSet(settings: WebSettings) {
        //开启 DOM storage API 功能 较大存储空间，使用简单
        settings.setDomStorageEnabled(true)
        //开启 Application Caches 功能 方便构建离线APP 不推荐使用
        settings.setAppCacheEnabled(true)

    }

    private fun initWebViewClient(webView: DWebView) {
//        webView.setWebViewCallbackClient()
//        webView.setWebChromeClientExtension()
        webView.webViewClient = object : WebViewClient() {
            override fun shouldInterceptRequest(
                view: WebView?,
                request: WebResourceRequest?
            ): WebResourceResponse? {
                Timber.d("shouldInterceptRequest()..11..request=${request?.url}")
                if (request != null) {
//                    val res = GlideImgCacheManager.interceptRequest(view, request.getUrl().toString())
//                    if (res != null) {
//                        Timber.d("res不为空...1111...")
//                        return res;
//                    }
                }
                return super.shouldInterceptRequest(view, request)
            }

            override fun shouldInterceptRequest(p0: WebView?, request: WebResourceRequest?, p2: Bundle?): WebResourceResponse {
                Timber.d("shouldInterceptRequest()..222..request=${request?.url}")
                return super.shouldInterceptRequest(p0, request, p2)
            }

            override fun shouldOverrideUrlLoading(p0: WebView?, request: WebResourceRequest?): Boolean {
                Timber.d("shouldOverrideUrlLoading()..3333..request=${request?.url}")
                return super.shouldOverrideUrlLoading(p0, request)
            }
        }
    }

    fun f1() {

    }

    private fun initGlideView() {
        vm.viewModelScope.launch(Dispatchers.IO) {
            Glide.get(Utils.getApp()).clearDiskCache()
            Timber.d("清除硬盘缓存...111..name=${Thread.currentThread().name}")
            withResumed {
                Timber.d("清除内存缓存...222..name=${Thread.currentThread().name}")
                Glide.get(Utils.getApp()).clearMemory()
                binding.iv1.setImageDrawable(null)
                binding.iv2.setImageDrawable(null)
                binding.iv3.setImageDrawable(null)
                val headUrl1 =
                    "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F0116db5b63b27da801215c8fd1f251.jpg%401280w_1l_2o_100sh.jpg&refer=http%3A%2F%2Fimg.zcool.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1629361624&t=4d8918782bea37549e7246332d79f3af"
                val headUrl2 = "https://media-ruhr.oss-cn-beijing.aliyuncs.com/1604974480583.png"
                val headUrl3 = "https://media-ruhr.oss-cn-beijing.aliyuncs.com/1602665128517.png"
                GlideImageUtils.load_img(binding.iv1, headUrl1)
                GlideImageUtils.load_img(binding.iv2, headUrl2)
                GlideImageUtils.load_img(binding.iv3, headUrl3)
            }
        }
    }

    private fun initView() {
        dwebView = binding.dWebView
        dwebView2 = binding.dWebView2
        //  nativeWebView = binding.nativeWebView
        binding.btn1.setOnClickListener { onClickBtn1() }
        binding.btn2.setOnClickListener { onClickBtn2() }
        binding.btn3.setOnClickListener { onClickBtn3() }
        binding.btn4.setOnClickListener { onClickBtn4() }

    }


    var url_def_flag = 1
    var url_1360768_flag = 2
    var url_160012008_flag = 3
    var url_wuhuoyuan_flag = 4
    private val url_flagMap = SparseArray<Int>()
    fun getUrl(flag: Int): String {
        var index = 0
        if (url_flagMap[flag] == null) {
            index = flag
        } else {
            index = flag + 1
        }
        if (index > 4) {
            index %= 4
        }

        url_flagMap.put(flag, index)
        when (flag) {
            url_def_flag -> {
                return UrlConfig.test_url
            }
            url_1360768_flag -> {
                return UrlConfig.test_url_1360768
            }
            url_160012008_flag -> {
                return UrlConfig.test_url_16001200
            }
            else -> {
                return UrlConfig.wuhuoyuan_url
            }
        }
    }

    fun onClickBtn1() {
        dwebView.clearCache(false) // 即使传false,也可以让h5里的图片再次请求
        dwebView.loadUrl(getUrl(url_1360768_flag))
    }

    fun onClickBtn2() {
//        dwebView2.loadUrl(getUrl(url_160012008_flag))

        initGlideView()
    }

    fun onClickBtn4() {
        ActivityUtils.startActivity(WebViewActivity::class.java)
    }
    fun onClickBtn3() {
        if (3 == 33) {
            val settings = nativeWebView.settings
            settings.javaScriptEnabled = true
            nativeWebView.loadUrl("")

        } else {
            ActivityUtils.startActivity(SecondAct::class.java)
        }
    }
}